/*
 * Copyright (c) 2007-2008, Thomas Krause (tho.krause@gmail.com)
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of gidoo nor the names of its contributors may be used to
 *       endorse or promote products derived from this software without specific
 *       prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.gidoo.cms.admin.addins;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
import org.gidoo.cms.admin.AdminPage;
import org.gidoo.cms.login.GidooCMSSession;

/**
 * A panel where you can adminstrate a single section.
 * @author Thomas
 */
public class SingleSectionPanel extends AddInPanel
{
    
  private Form formDelete;
  private Button btDelete;
  
  private Form formOrder;
  
  private Form formChange;
  private TextField txtURL;
  private TextField txtName;
  
  private String theSection;
  private AdminPage theParent;
  
  /**
   * Creates a new instance of UsersPanel
   * @param id The wicket id.
   * @param section The name of the section.
   */
  public SingleSectionPanel(String id, String section, AdminPage parent)
  {
    super(id);
    this.theSection = section;
    this.theParent = parent;
    
    formChange = new Form("formChange");
    
    txtURL = new TextField("txtURL", new Model(""));
    txtName = new TextField("txtName", new Model(""));
    
    formChange.add(new Button("btChange", new Model(getString("change")))
    {
      @Override
      public void onSubmit()
      {
        try
        {
          String url = txtURL.getModelObjectAsString();
          String name = txtName.getModelObjectAsString();
          
          GidooCMSSession gs = (GidooCMSSession) getSession();
          Node rootNode = gs.getJcrRootNode();
          Session session = gs.getJcrSession();
          
          Node sectionsNode = rootNode.getNode("sections");
          String oldURL = 
            sectionsNode.getNode(theSection).getProperty("cms:url").getString();
          
          boolean canBeUpdated = true;
          if(!oldURL.equals(url))
          {
            
            QueryResult r = gs.getQueryManager().createQuery(
              "/jcr:root/sections/*[@cms:url = '" + url + "']", Query.XPATH).execute();

            if(r.getNodes().hasNext())
            {
              canBeUpdated = false;
            }
          }
          
          if(!theSection.equals(name))
          {
            if(sectionsNode.hasNode(name))
            {
              canBeUpdated = false;
            }
          }
          
          if(!canBeUpdated)
          {
            error(getString("alreadyexists"));
          }
          else
          {
            session.getWorkspace().move("/sections/" + theSection, "/sections/" + name);
            Node newNode = sectionsNode.getNode(name);
            newNode.setProperty("cms:url", url);
          
            newNode.save();
              
            // update all references (publishing and editing rights)
            QueryManager qm = session.getWorkspace().getQueryManager();
            QueryResult rEdit = qm.createQuery("/jcr:root/users/*/edit/" + theSection, Query.XPATH).execute();
            NodeIterator it = rEdit.getNodes();
            while(it.hasNext())
            {
              Node n = it.nextNode();
              session.getWorkspace().move(n.getPath(), n.getParent().getPath() + "/" + name);
            }
            QueryResult rPublish = qm.createQuery("/jcr:root/users/*/publish/" + theSection, Query.XPATH).execute();
            it = rPublish.getNodes();
            while(it.hasNext())
            {
              Node n = it.nextNode();
              session.getWorkspace().move(n.getPath(), n.getParent().getPath() + "/" + name);
            }
            
            theSection = name;
          }
          
          updateDataAndView();
          theParent.setSelectedNode(theParent.getSectionNode());
          theParent.updateDataAndView();
        }
        catch (RepositoryException ex)
        {
          Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
          error(getString("jcrerror"));
        }
      }      
    });
    
    formChange.add(txtName);
    formChange.add(txtURL);
    add(formChange);
    
    updateDataAndView();
    
    formDelete = new Form("formDelete");
    btDelete = new Button("btDelete", new Model(getString("deleteSection")))
    {
      
      @Override
      public void onSubmit()
      {
        try
        { 
          GidooCMSSession session = (GidooCMSSession) getSession();
          // delete all references (publishing and editing rights)
          QueryManager qm = session.getJcrSession().getWorkspace().getQueryManager();
          QueryResult rEdit = qm.createQuery("/jcr:root/users/*/edit/" + theSection, Query.XPATH).execute();
          NodeIterator it = rEdit.getNodes();
          while(it.hasNext())
          {
            it.nextNode().remove();
          }
          QueryResult rPublish = qm.createQuery("/jcr:root/users/*/publish/" + theSection, Query.XPATH).execute();
          it = rPublish.getNodes();
          while(it.hasNext())
          {
            it.nextNode().remove();
          }
          
          Node sectionsNode = session.getJcrRootNode().getNode("sections");
          sectionsNode.getNode(theSection).remove();
          
          session.getJcrSession().save();
          
          theParent.setSelectedNode(null);
          theParent.updateDataAndView();
        }
        catch(RepositoryException ex)
        {
          Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
          error(getString("jcrerror"));
        }
      }
      
    };
    
    formDelete.add(btDelete);
    add(formDelete);
    
    formOrder = new Form("formOrder");
    
    AjaxButton btUp = new AjaxButton("btUp") 
    {

      @Override
      protected void onSubmit(AjaxRequestTarget target, Form form)
      {
        sectionUp();
        target.addComponent(theParent.getTreeNav());
        target.addComponent(feedback);
      }
    };
    btUp.setModel(new Model(getString("up")));
    
    formOrder.add(btUp);
    
    AjaxButton btDown = new AjaxButton("btDown") {

      @Override
      protected void onSubmit(AjaxRequestTarget target, Form form)
      {
        sectionDown();
        target.addComponent(theParent.getTreeNav());
        target.addComponent(feedback);
      }
    };
    btDown.setModel(new Model(getString("down")));
    
    formOrder.add(btDown);
    
    add(formOrder);
    
    
  }
  
  private void sectionUp()
  {
    try
    {
      if (theSection == null)
      {
        return;
      }
      
      Node sNode = ((GidooCMSSession) getSession()).getJcrRootNode().getNode("sections");
      NodeIterator it = sNode.getNodes();
      
      Node lastNode = null;
      
      while (it.hasNext())
      {
        Node c = it.nextNode();
        if(c.getName().equals(theSection))
        {
          if(lastNode != null)
          {
            sNode.orderBefore(theSection, lastNode.getName());
            sNode.save();
          }
          break;
        }
        else
        {
          lastNode = c;
        }
      }

      theParent.updateTreeModel(null, theSection);
    }
    catch (RepositoryException ex)
    {
      Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("jcrerror"));
    }    
    
  }
  
  private void sectionDown()
  {
      try
    {
      if (theSection == null)
      {
        return;
      }
      
      Node sNode = ((GidooCMSSession) getSession()).getJcrRootNode().getNode("sections");
      NodeIterator it = sNode.getNodes();
      
      while (it.hasNext())
      {
        Node c = it.nextNode();
        if(c.getName().equals(theSection))
        {
          if(it.hasNext())
          {
            sNode.orderBefore(it.nextNode().getName(), theSection);
            sNode.save();
          }
          break;
        }
      }

      theParent.updateTreeModel(null, theSection);
    }
    catch (RepositoryException ex)
    {
      Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("jcrerror"));
    }
  }
  
  private void updateDataAndView()
  {
    try
    {
      lblTitle.setModelObject(getString("title") + theSection);

      Node s = ((GidooCMSSession) getSession()).getJcrRootNode().getNode("sections").getNode(theSection);

      txtName.setModelObject(theSection);
      txtURL.setModelObject(s.getProperty("cms:url").getString());
    }
    catch (RepositoryException ex)
    {
      Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
    
  }
  
}
